package com.study.springbootsecurity.util;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.study.springbootsecurity.config.properties.AliyunSmsProperties;
import com.study.springbootsecurity.exception.BusinessException;
import darabonba.core.client.ClientOverrideConfiguration;
import jakarta.annotation.PreDestroy;
import lombok.Data;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.baomidou.mybatisplus.extension.ddl.DdlScriptErrorHandler.PrintlnLogErrorHandler.log;

/**
 * @Description: TODO 初始化客户端
 * @author: Huangjianyun
 * @date: 2025-06-16 14:52
 */
@Component
@Data
public class SmsClientFactory {
    private final static Logger logger = LoggerFactory.getLogger(SmsClientFactory.class);
    private final AliyunSmsProperties smsProperties;
    private  AsyncClient asyncClient;

    @Autowired
    public SmsClientFactory(AliyunSmsProperties smsProperties) {
        this.smsProperties = smsProperties;
        this.asyncClient = initClient();
    }

    // 添加初始化客户端方法
    public AsyncClient initClient() {
        try{
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                    .build());
            return AsyncClient.builder()
                    .region(smsProperties.getRegion()) // Region ID
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride(smsProperties.getEndpoint())
                    )
                    .build();
        }catch (Exception e){
            logger.error("初始化aliyun短信服务客户端失败");
            throw new BusinessException(-1,"初始化aliyun短信服务客户端失败");
        }
    }


    // 销毁客户端
    @PreDestroy
    public void destroy() {
        try{
            if (ObjectUtils.isNotEmpty(asyncClient)) {
                try {
                    asyncClient.close();
                    log.debug("短信客户端已关闭");
                } catch (Exception e) {
                    log.error("关闭短信客户端时发生异常",e);
                }
        }
    }catch (Exception e){
        logger.error("关闭短信服务失败");
        throw new BusinessException("关闭短信服务失败");
        }
    }
}
